<script>
import { Upload } from 'element-ui'
import QRCode from 'qrcode'
import { getFileUploadCode, getFileUrlByCode } from '@const/fileLibraryApi.js'
import { hasIn } from 'lodash'
export default {
  name: 'AutoUpload',
  components: { mUpload: Upload },
  data () {
    return {
      qrcodeImg: '',
      backVisible: false,
      qrcodeLoading: false,
      code: '',
      loopData: {},
      key: 1
    }
  },
  methods: {
    qrcodeBtn () {
      this.backVisible = true
      this.qrcodeLoading = true
      let originUrl = window.location.origin.includes('.com')
        ? window.location.origin
        : process.env.guokeChannelServeDev
      this.$axios({
        url: getFileUploadCode,
        method: 'post'
      }).then(res => {
        let code = hasIn(res, ['data', 'payload']) ? res.data.payload : ''
        if (!code) {
          this.$message({
            type: 'warning',
            message: '获取状态码失败，请联系管理员！'
          })
          return
        }
        this.code = code
        QRCode.toDataURL(
          `${originUrl}/guoke-deepexi-utils-server-h5/#/file?token=${this.$store.state.token}&code=${code}`
        )
          .then(url => {
            this.qrcodeImg = url
            this.getQrcodeImgUrl(10)
            this.qrcodeLoading = false
          })
          .catch(() => {
            this.$message({
              type: 'error',
              message: '生成二维码失败，建议使用本地上传！'
            })
          })
      })
    },
    // 取消提示
    cancleConfirm () {
      this.$confirm(
        '还未检测到通过二维码上传的文件，是否取消二维码上传?',
        '提示',
        {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }
      )
        .then(() => {
          this.backVisible = false
          this.loopData[this.key] = true
        })
        .catch(() => {
          this.qrcodeLoading = false
          this.getQrcodeImgUrl(10)
        })
    },
    // 睡觉函数
    async sleep (seconds) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve()
        }, seconds * 1000)
      })
    },
    async getQrcodeImgUrl (count, key = this.key) {
      for (let index = 0; index < count; index++) {
        if (this.loopData[key] || !this.backVisible) {
          return false
        }
        // 3秒一次 最多5次
        await this.sleep(3)
        // this.qrcodeLoading = true
        if (this.loopData[key] || !this.backVisible) {
          return false
        }
        const responseData = await this.$axios({
          url: getFileUrlByCode,
          method: 'post',
          data: { code: this.code }
        })
        if (this.loopData[key] || !this.backVisible) {
          return false
        }
        if (responseData.data.code === '0') {
          let imgUrl = hasIn(responseData, ['data', 'payload']) ? responseData.data.payload : ''
          if (!imgUrl) {
            continue
          }
          let mProps = this.$attrs['m-props']
          mProps.urlObj[mProps.urlStr] = imgUrl
          this.backVisible = false
          return false
        }
      }
      // 关闭二维码模态窗
      if (this.backVisible) {
        this.backVisible = false
      }
    },
    // 暂时不用
    async backClick () {
      this.qrcodeLoading = true
      this.loopData[this.key] = true
      this.key++
      const responseData = await this.$axios({
        url: getFileUrlByCode,
        method: 'post',
        data: { code: this.code }
      })
      try {
        if (responseData.data.code === '0') {
          let imgUrl = hasIn(responseData, ['data', 'payload']) ? responseData.data.payload : ''
          if (!imgUrl) {
            this.cancleConfirm()
            return false
          }
          let mProps = this.$attrs['m-props']
          mProps.urlObj[mProps.urlStr] = imgUrl
          this.backVisible = false
          return false
        }
      } catch (err) {
        console.log(err)
        this.backVisible = false
        this.$message({
          type: 'warning',
          message: '获取上传图片失败，建议使用本地上传！'
        })
      }
    }
  },
  render (h) {
    const attrsMethods = slots => {
      let values = Object.values(slots)
      let sList = []
      values.forEach(vnodes => {
        sList.push(vnodes)
      })
      return sList
    }
    const qrcodeShow = h => {
      return this.backVisible
        ? h(
          'div',
          {
            class: { 'back-mask': true },
            on: {
              click: this.backClick
            }
          },
          this.qrcodeImg
            ? [
              h('el-image', {
                class: { 'back-qrcode-img': true },
                directives: [{ name: 'loading', value: this.qrcodeLoading }],
                props: { fit: 'fitType', src: this.qrcodeImg }
              }),
              h(
                'span',
                {
                  class: { 'qrcode-icon': true }
                },
                [
                  h('icon-font', {
                    props: { icon: 'el-icon-mobile-phone' }
                  })
                ]
              )
            ]
            : []
        )
        : []
    }
    const qrcodeBtn = h => {
      return h('i', { class: { 'iconfont icon-qrcode': true } })
    }
    return h('div', { class: { qrcode_upload_box: true } }, [
      h(
        'm-upload',
        {
          props: this.$attrs,
          on: this.$listeners,
          ref: 'mUpload'
        },
        attrsMethods(this.$slots)
      ),
      h(
        'el-button',
        {
          class: { qrcode_box: true },
          props: {
            circle: true,
            type: 'primary',
            disabled: this.$attrs.disabled
          },
          attrs: { title: '手机上传二维码' },
          on: {
            click: this.qrcodeBtn
          }
        },
        [qrcodeBtn(h)]
      ),
      qrcodeShow(h)
    ])
  }
}
</script>
<style lang="less" scoped>
.qrcode_upload_box {
  position: relative;
  width: 100%;
  height: 100%;
  .qrcode_box {
    position: absolute;
    top: -16px;
    right: 0;
    transform: translate(50%, 50%);
    z-index: 99;
  }

  .icon-qrcode {
    font-size: 24px;
  }

  .back-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 100;
    display: flex;
    align-items: center;
    justify-content: center;
    .back-qrcode-img {
      width: 250px;
      height: 250px;
    }
    .qrcode-icon {
      position: fixed;
      width: 50px;
      height: 50px;
      background-color: rgba(255, 255, 255, 0.9);
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      > i {
        font-size: 40px;
      }
    }
  }
}
</style>
